<?php
/**
 * Created by PhpStorm.
 * User: zq
 * Date: 2017/2/22
 * Time: 11:47
 */

namespace Admin\Controller;


use Common\Controller\AdminController;
use Common\Model\CategoryModel;
use Org\Util\DataTree;

class CategoryController extends AdminController
{
    public function index(){
        $cateData = m('category')->select();
//        dump($cateData);die;
        $cateData = (new DataTree())->tree($cateData,'cname');
//        dump($cateData);die;
        $this->assign('cateData',$cateData);
        $this->display();
    }
    public function add(){
        $id = I('get.cid');
        $pid = I('get.pid');
        if(IS_POST){
//            dump($_POST);die;
            $data = I('post.');
            $data['pid'] = $pid;
            if($id){
                $data['cid'] =$id;
            }
//            dump($data);die;
            $this->store(new CategoryModel(),$data,function(){
                $this->success('操作成功',u('Category/index'));die;
            });
        }
        //分配旧数据
        if($id){
            $oldData = m('category')->find($id);
        }else{
            $oldData =[];
        }
        $this->assign('oldData', $oldData);

        //分配父级ID
        $this->pid = isset($_GET['pid']) ? (int) $_GET['pid'] : 0;

        //如果添加的是子分类，分配类型选择，即顶级分类没有类型
        if($this->pid > 0){
            $this->type = M('type')->select();
        }
        $this->display();
    }
    public function delCate(){
        $id =I('get.cid');
        $model = new CategoryModel();
        if($model->where("cid={$id}")->delete()){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

}